package com.dage.salesflow.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.dage.salesflow.excel.AutoColumnWidthStyleStrategy;
import com.dage.salesflow.excel.ExcelWriteHandler;
import com.dage.salesflow.model.vo.SelectOption;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.web.controller.JbootController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class BaseController extends JbootController {
	protected void renderPageJson(Page page) {
		renderJson(Kv.by("code", 0).set("msg", "").set("count", page.getTotalRow()).set("data", page.getList()));
	}

	protected List<Kv> modelListToSelect(List list) {
		List<Kv> options = new ArrayList<>();
		for (Object obj : list) {
			if (obj instanceof SelectOption) {
				SelectOption option = (SelectOption) obj;
				options.add(Kv.by("value", option.getValue()).set("text", option.getText()));
			}
		}
		return options;
	}

	protected File importTemplateFile(Class excelClass) throws IOException {
		Path tempFile = Files.createTempFile("导入模板" + System.currentTimeMillis(), ".xlsx");
		File file = tempFile.toFile();
		EasyExcel.write(file, excelClass)
				.registerWriteHandler(new ExcelWriteHandler(excelClass, true))
				.registerWriteHandler(new AutoColumnWidthStyleStrategy())
				.sheet("Sheet1")
				.doWrite(ListUtils.newArrayList());
		return file;
	}
}
